<template>
  <div class="apple-style-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">激活提成明细</h1>
      
      <!-- 筛选和导出按钮 -->
      <div class="action-buttons">
        <el-button class="apple-button filter-button" @click="openFilterDialog">
          <el-icon><Filter /></el-icon>
          <span>筛选</span>
        </el-button>
        <el-button class="apple-button export-button" @click="handleExport">
          <el-icon><Download /></el-icon>
          <span>导出</span>
        </el-button>
      </div>
    </div>
    
    <!-- 筛选标签展示区 -->
    <div v-if="hasActiveFilters" class="filter-tags-container">
      <div class="filter-tag" v-if="queryParams.nickname">
        <span>员工: {{ queryParams.nickname }}</span>
        <el-icon class="clear-icon" @click="clearFilter('nickname')"><Close /></el-icon>
      </div>
      <div class="filter-tag" v-if="queryParams.date_start && queryParams.date_end">
        <span>日期: {{ formatDate(queryParams.date_start) }} 至 {{ formatDate(queryParams.date_end) }}</span>
        <el-icon class="clear-icon" @click="clearFilter('date')"><Close /></el-icon>
      </div>
      <div class="filter-tag" v-if="queryParams.product_name">
        <span>产品: {{ queryParams.product_name }}</span>
        <el-icon class="clear-icon" @click="clearFilter('product_name')"><Close /></el-icon>
      </div>
      <div class="clear-all" @click="clearAllFilters">清除全部</div>
    </div>
    
    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon><Money /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">总提成金额</div>
          <div class="stat-value">{{ totalCommission.toFixed(2) }}</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">激活订单数</div>
          <div class="stat-value">{{ total }}</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">激活人数</div>
          <div class="stat-value">{{ uniqueUsers.length }}</div>
        </div>
      </div>
    </div>
    
    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="commissionList"
        border
        style="width: 100%"
        :header-cell-style="headerCellStyle"
        :cell-style="cellStyle"
        highlight-current-row
      >
        <el-table-column type="selection" width="45" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="nickname" label="昵称" min-width="80">
          <template #default="scope">
            <div class="nickname-cell">{{ scope.row.nickname }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="month" label="月份" min-width="80">
          <template #default="scope">
            {{ formatDate(scope.row.activation_date, 'YYYY-MM') }}
          </template>
        </el-table-column>
        <el-table-column prop="order_date" label="下单日期" min-width="100">
          <template #default="scope">
            {{ formatDate(scope.row.order_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="activation_date" label="激活日期" min-width="100">
          <template #default="scope">
            {{ formatDate(scope.row.activation_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="order_number" label="订单号" min-width="150">
          <template #default="scope">
            <div class="order-number">{{ scope.row.order_number }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="customer_name" label="客户名称" min-width="150">
          <template #default="scope">
            <div class="customer-name">{{ scope.row.customer_name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="产品名称" min-width="130">
          <template #default="scope">
            <div class="product-tag">{{ scope.row.product_name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="order_amount" label="订单金额" min-width="100">
          <template #default="scope">
            <div class="amount">{{ scope.row.order_amount.toFixed(2) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="commission_ratio" label="提成比例" min-width="90">
          <template #default="scope">
            <div class="ratio-badge">{{ (scope.row.commission_ratio * 100).toFixed(0) }}%</div>
          </template>
        </el-table-column>
        <el-table-column prop="commission" label="提成金额" min-width="100">
          <template #default="scope">
            <div class="commission-amount">{{ scope.row.commission.toFixed(2) }}</div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </div>

    <!-- 筛选弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="筛选条件"
      width="500px"
      class="apple-dialog"
    >
      <el-form :model="filterForm" label-width="100px">
        <el-form-item label="员工">
          <el-select v-model="filterForm.nickname" placeholder="请选择员工" clearable class="apple-select">
            <el-option
              v-for="item in employeeOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.nickname"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="apple-date-picker"
          />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-select v-model="filterForm.product_name" placeholder="请选择产品" clearable class="apple-select">
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提成金额范围">
          <div class="range-input">
            <el-input v-model="filterForm.min_commission" placeholder="最小金额" class="apple-input" />
            <span class="range-separator">至</span>
            <el-input v-model="filterForm.max_commission" placeholder="最大金额" class="apple-input" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetFilter" class="apple-button-secondary">重置</el-button>
          <el-button type="primary" @click="confirmFilter" class="apple-button-primary">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { getCommissionDetails, exportCommissionDetails } from '@/api/orders'
import { getCustomerServiceUsers } from '@/api/salary'
import { ElMessage } from 'element-plus'
import { Filter, Download, Close, Money, Document, User } from '@element-plus/icons-vue'

// 定义组件名称
defineOptions({
  name: 'CommissionDetailPage'
})

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  date_start: '',
  date_end: '',
  nickname: '',
  product_name: '',
  min_commission: '',
  max_commission: ''
})

// 筛选表单数据
const filterForm = reactive({
  nickname: '',
  product_name: '',
  min_commission: '',
  max_commission: ''
})
const dateRange = ref([])

// 筛选弹窗可见性
const dialogVisible = ref(false)

// 数据列表
const commissionList = ref([])
const total = ref(0)
const loading = ref(false)

// 计算属性：总提成金额
const totalCommission = computed(() => {
  return commissionList.value.reduce((sum, item) => sum + (item.commission || 0), 0)
})

// 计算属性：唯一用户列表
const uniqueUsers = computed(() => {
  const users = new Set()
  commissionList.value.forEach(item => {
    if (item.nickname) {
      users.add(item.nickname)
    }
  })
  return Array.from(users)
})

// 计算属性：判断是否有活跃的筛选条件
const hasActiveFilters = computed(() => {
  return !!(queryParams.nickname || 
    queryParams.product_name || 
    (queryParams.date_start && queryParams.date_end) ||
    queryParams.min_commission ||
    queryParams.max_commission)
})

// 表格样式
const headerCellStyle = () => {
  return {
    background: '#f5f7fa',
    color: '#606266',
    fontWeight: 600,
    fontSize: '14px',
    height: '50px',
    padding: '0 12px'
  }
}

const cellStyle = () => {
  return {
    fontSize: '14px',
    padding: '12px'
  }
}

// 员工选项
const employeeOptions = ref([])
// 产品选项
const productOptions = ref([
  { value: 'Elementor Pro', label: 'Elementor Pro' },
  { value: 'WPForms', label: 'WPForms' },
  { value: 'ACF', label: 'ACF' },
  { value: 'TranslatePress Pro', label: 'TranslatePress Pro' }
])

// 获取员工选项
const getEmployeeOptions = async () => {
  try {
    const response = await getCustomerServiceUsers()
    if (response.code === 200 && response.data) {
      // 转换API返回的数据格式以适配下拉框
      employeeOptions.value = response.data.map(item => ({
        id: item.value,
        nickname: item.label
      }))
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  }
}

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    const response = await getCommissionDetails(queryParams)
    
    if (response && response.code === 200) {
      commissionList.value = response.data.items || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error('获取提成明细失败')
      commissionList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取提成明细失败:', error)
    ElMessage.error('系统错误，请稍后重试')
    commissionList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 导出提成明细
const handleExport = async () => {
  try {
    loading.value = true
    ElMessage.info('正在导出数据，请稍候...')
    
    // 构建导出参数，使用当前的筛选条件
    const exportParams = {
      date_start: queryParams.date_start,
      date_end: queryParams.date_end,
      nickname: queryParams.nickname,
      product_name: queryParams.product_name,
      min_commission: queryParams.min_commission,
      max_commission: queryParams.max_commission
    }
    
    const response = await exportCommissionDetails(exportParams)
    
    // 创建Blob对象
    const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
    
    // 创建下载链接
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    
    // 生成文件名，包含当前日期
    const currentDate = new Date().toISOString().split('T')[0]
    link.download = `提成明细_${currentDate}.xlsx`
    
    // 模拟点击下载
    link.click()
    URL.revokeObjectURL(link.href)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出提成明细失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr, format = 'YYYY-MM-DD') => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  
  if (format === 'YYYY-MM') {
    return `${year}-${month}`
  }
  
  return `${year}-${month}-${day}`
}

// 打开筛选弹窗
const openFilterDialog = () => {
  // 初始化筛选表单的值为当前查询参数的值
  filterForm.nickname = queryParams.nickname
  filterForm.product_name = queryParams.product_name
  filterForm.min_commission = queryParams.min_commission
  filterForm.max_commission = queryParams.max_commission
  
  // 设置日期范围
  if (queryParams.date_start && queryParams.date_end) {
    dateRange.value = [queryParams.date_start, queryParams.date_end]
  } else {
    dateRange.value = []
  }
  
  dialogVisible.value = true
}

// 确认筛选
const confirmFilter = () => {
  queryParams.nickname = filterForm.nickname
  queryParams.product_name = filterForm.product_name
  queryParams.min_commission = filterForm.min_commission
  queryParams.max_commission = filterForm.max_commission
  
  // 处理日期范围
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.date_start = dateRange.value[0]
    queryParams.date_end = dateRange.value[1]
  } else {
    queryParams.date_start = ''
    queryParams.date_end = ''
  }
  
  // 重置为第一页
  queryParams.page = 1
  
  // 关闭弹窗并刷新数据
  dialogVisible.value = false
  getList()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.nickname = ''
  filterForm.product_name = ''
  filterForm.min_commission = ''
  filterForm.max_commission = ''
  dateRange.value = []
}

// 清除单个筛选条件
const clearFilter = (type) => {
  if (type === 'nickname') {
    queryParams.nickname = ''
  } else if (type === 'date') {
    queryParams.date_start = ''
    queryParams.date_end = ''
  } else if (type === 'product_name') {
    queryParams.product_name = ''
  } else if (type === 'commission') {
    queryParams.min_commission = ''
    queryParams.max_commission = ''
  }
  
  // 重新加载数据
  getList()
}

// 清除所有筛选条件
const clearAllFilters = () => {
  queryParams.nickname = ''
  queryParams.product_name = ''
  queryParams.date_start = ''
  queryParams.date_end = ''
  queryParams.min_commission = ''
  queryParams.max_commission = ''
  
  // 重新加载数据
  getList()
}

// 分页大小改变事件
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

// 当前页改变事件
const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 组件挂载后执行
onMounted(() => {
  getEmployeeOptions()
  getList()
})
</script>

<style scoped>
.apple-style-container {
  padding: 0 10px 10px 10px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  background-color: #f5f5f7;
  min-height: calc(100vh - 100px);
  max-width: 98%;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.apple-button {
  border-radius: 20px;
  height: 40px;
  padding: 0 20px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  background: rgba(0, 0, 0, 0.05);
  color: #1d1d1f;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.apple-button:hover {
  background: rgba(0, 0, 0, 0.1);
}

.apple-button-primary {
  background: #0071e3;
  color: white;
  border-radius: 20px;
  border: none;
  transition: all 0.3s ease;
}

.apple-button-primary:hover {
  background: #0077ed;
  opacity: 0.9;
}

.apple-button-secondary {
  background: rgba(0, 0, 0, 0.05);
  color: #1d1d1f;
  border-radius: 20px;
  border: none;
  transition: all 0.3s ease;
}

.apple-button-secondary:hover {
  background: rgba(0, 0, 0, 0.1);
}

.filter-tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.filter-tag {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 16px;
  font-size: 13px;
  color: #1d1d1f;
  gap: 8px;
}

.clear-icon {
  cursor: pointer;
  font-size: 12px;
  color: #86868b;
}

.clear-icon:hover {
  color: #1d1d1f;
}

.clear-all {
  font-size: 13px;
  color: #0071e3;
  cursor: pointer;
  margin-left: 10px;
}

.clear-all:hover {
  text-decoration: underline;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.stat-icon {
  width: 42px;
  height: 42px;
  background: #f5f5f7;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #0071e3;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #86868b;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #1d1d1f;
}

.table-card {
  background: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  width: 100%;
  overflow-x: auto;
}

/* 表格中的特殊样式 */
.nickname-cell {
  font-weight: 500;
  color: #0071e3;
}

.order-number {
  font-family: monospace;
  color: #1d1d1f;
}

.customer-name {
  font-weight: 500;
}

.product-tag {
  display: inline-block;
  padding: 4px 8px;
  background-color: rgba(0, 113, 227, 0.08);
  color: #0071e3;
  border-radius: 4px;
  font-size: 12px;
}

.amount {
  font-family: monospace;
  font-weight: 500;
}

.ratio-badge {
  display: inline-block;
  padding: 2px 8px;
  background-color: rgba(52, 199, 89, 0.1);
  color: #34c759;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 500;
}

.commission-amount {
  font-family: monospace;
  font-weight: 600;
  color: #f56c6c;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

/* 苹果风格的弹窗和表单样式 */
:deep(.apple-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.apple-dialog .el-dialog__header) {
  background: #f5f5f7;
  padding: 20px;
  margin: 0;
}

:deep(.apple-dialog .el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
}

:deep(.apple-dialog .el-dialog__body) {
  padding: 24px;
}

:deep(.apple-dialog .el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.apple-select {
  width: 100%;
}

:deep(.apple-select .el-input__wrapper),
:deep(.apple-date-picker .el-input__wrapper),
:deep(.apple-input .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
  transition: box-shadow 0.3s ease;
}

:deep(.apple-select .el-input__wrapper:hover),
:deep(.apple-date-picker .el-input__wrapper:hover),
:deep(.apple-input .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-select .el-input__wrapper.is-focus),
:deep(.apple-date-picker .el-input__wrapper.is-focus),
:deep(.apple-input .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

.range-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-separator {
  color: #86868b;
}
</style> 